<?php

namespace CNEPAdmin\Model;

use Think\Model;

class SysAdminModel extends Model {

    protected $_validate = array(/* array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]) */
        array('account', 'require', '帐号不能为空！'),
        array('account', '', '帐号已经存在！', 0, 'unique', 1),
        array('email', 'email', '邮箱格式错误！', 2), // 值不为空时验证
        array('rePassword', 'password', '确认密码不正确', 0, 'confirm'), // 验证确认密码是否和密码一致
        array('password', '3,12', '密码长度必须在3到12个字符', 0, 'length'), // 密码长度3~12
        array('oldPassword', 'checkOldPsw', '旧密码错误！', 0, 'callback', 2),
    );  // 自动验证定义
    protected $_auto = array(/* array(完成字段1,完成规则,[完成条件,附加规则]) */
        array('addTime', 'time', 1, 'function'),
        array('updateTime', 'time', 2, 'function'),
        array('isOn', '1', 1),
        array('lastLogin', 'time', 4, 'function'), // 登录时候
        array('lastIp', 'get_client_ip', 4, 'function')
    );  // 自动完成定义

    public function checkOldPsw() {
        $adminid = I("session.adminid");
        $oldPsw = I("post.oldPassword");
        $data['adminID'] = $adminid;
        $dbPsw = $this->where($data)->getField("password");

        return ($oldPsw === $dbPsw);
    }

    public function addAdmin($data = '') {
        $rt = false;

        if ($this->create($data)) {
            $rt = $this->add();
        }
        return $rt;
    }

    /**
     * 根据id更新属性（除密码）
     * @param type $adminID
     * @param type $key
     * @param type $val
     */
    public function updateMsg($data = '') {
        $rt = false;

        if ($this->create($data)) {
            $rt = $this->save();
        }
        return $rt;
    }

    /**
     * 根据id更新一个属性（除密码）
     * @param type $id 
     * @param type $key
     * @param type $val
     */
    public function updateOneFieldById($id, $key, $val) {
        if ($id <= 0) {
            $this->error = "无效ID";
            return false;
        }
        $data[$key] = $val;
        $data['adminID'] = $id;
        $data['updateTime'] = time();
        return $this->data($data)->save();
    }

    public function deleteAdmin($id) {
        return $this->updateOneFieldById($id, 'isOn', 0);
    }

    public function getAdmin($id) {
        if ($id <= 0) {
            $this->error = "无效";
            return false;
        }
        return $this->where("adminID=$id")->find();
    }

    public function getAdminList($pageNo = 1, $pageSize = 15, $where = array(), $order = array()) {
        $rt = $this->where($where)->page("$pageNo,$pageSize")->order($order)->select();
        return $rt;
    }

    public function getAdminListLength($where = array()) {
        return $this->where($where)->count();
    }

    public function getOneField($where = '',$field = '') {
        return $this->where($where)->getField($field);
    }
    
}

?>